package com.guigu.aclservice.service.impl.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.aclservice.entity.User;
import com.guigu.aclservice.mapper.UserMapper;
import com.guigu.aclservice.service.UserService;
import com.guigu.commonutils.JwtUtils;
import com.guigu.commonutils.MD5;
import com.guigu.servicebase.exceptionhandler.MyCustomeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @Author: janecraft
 * @Date: 2022/6/2
 * @Description: com.guigu.aclservice.service.impl.impl
 * @Version： 1.0
 */
@Service
public class UserServiceImpl
        extends ServiceImpl<UserMapper, User>
            implements UserService {
    @Autowired(required = false)
    private UserMapper userMapper;

    @Override
    public String canLogin(String username, String password) {
        if(StringUtils.isEmpty(username))
            throw new MyCustomeException(20010, "用户名为空");
        if(StringUtils.isEmpty(password))
            throw new MyCustomeException(20011, "密码为空");
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        User user = userMapper.selectOne(wrapper);
        if(user == null)
            throw new MyCustomeException(20012, "用户不存在");

        if(!MD5.encrypt(password).equals(user.getPassword()))
            throw new MyCustomeException(20013, "用户名或者密码不正确");

        // 身份验证成功
        String jwtToken = JwtUtils.getJwtToken(user.getId(), user.getNickName());

        return jwtToken;
    }
}
